var toPage;
$(function () {
    formValidation();
    loadMaintenanceData();
})
laydate.render({
    elem: '#validationCustom03',
    type: 'datetime',
    done: function (value) {
        $('#validationCustom03').val(value);
        $('#validationCustom03').trigger('input');
    }
});
laydate.render({
    elem: '#searchTimeBegin',
    max: 0
});
laydate.render({
    elem: '#searchTimeEnd',
    max: 0
});

function formValidation() {
    $('#addInfoForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',

            validating: 'fa fa-sync-alt'
        },
        fields: {
            sn: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 2,
                        max: 25
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_]+$/,
                        message: '设备编号只能由字母、数字和下划线组成'
                    },
                    threshold: 2, //设置4字符以上开始请求服务器
                    //有待验证，备注以备下次使用。
                    //bootstrap的remote验证器需要的返回结果一定是json格式的数据 :
                    //{"valid":false} //表示不合法，验证不通过
                    //{"valid":true} //表示合法，验证通过
                    remote: {//发起Ajax请求。
                        url: '../device/verificationDeviceByNumber',//验证地址
                        data: {'sn': $('input[name="sn"]').val(), 'type': 0},
                        message: '未查询到设备信息',//提示消息
                        delay: 1000,//设置2秒发起名字验证
                        type: 'POST' //请求方式
                    }
                }
            }, content: {
                validators: {
                    notEmpty: {
                        message: '维保内容不能为空',
                    },
                }
            },
            maintenanceTime: {
                validators: {
                    notEmpty: {
                        message: '维保时间不能为空',
                    },
                }
            },
        }
    }).on('success.form.bv', function (e) {
        //防止表单提交
        e.preventDefault();
        //获取表单实例
        var $form = $(e.target);
        //获取BootstrapValidator实例
        var bv = $form.data('bootstrapValidator');
        ////使用Ajax提交表单数据
        $.ajax({
            url: "../maintenance/saveOrUpdateCollectionMaintenance",
            type: 'POST',
            data: $form.serialize(),
            datatype: 'json',
            beforeSend: function (xhr) {
                xhr.setRequestHeader('token', sessionStorage.getItem("token"));
            },
            success: function (data) {
                if (data.code == 200) {
                    myAlert("提示", "保存成功", function () {
                        loadMaintenanceData(toPage);
                        return;
                    })
                }
                myAlert("提示", data.message)
            },
            error: function (data) {
                myAlert("提示", "保存失败")
            }
        });
    }).on('error.form.bv', function (e) { //点击提交验证失败之后
        $('[type="submit"]').removeAttr("disabled");
    });
}

/*添加*/
function addInfo() {
    $("#addInfoForm").data('bootstrapValidator').destroy();
    $('#addInfoForm').data('bootstrapValidator', null);
    formValidation();
    $('#modal_title').text('添加设备病例');
    $('#addInfoForm')[0].reset();//清空表单
    $('#validationCustom01').removeAttr("readonly");
    $('#addInfoModal').modal();
}

/*修改信息*/
function editInfo(e) {
    $("#addInfoForm").data('bootstrapValidator').destroy();
    $('#addInfoForm').data('bootstrapValidator', null);
    formValidation();
    $('#addInfoForm')[0].reset();//清空表单
    $('#validationCustom01').attr("readonly", "readonly");
    $('#id-id').val(e);
    $('#method-id').val(1);
    $('#modal_title').text('修改设备病例信息');
    getJson("/maintenance/getMaintenanceBayId",{"id": e},'GET',function (result) {
        $('#validationCustom01').val(result.sn);
        $('#validationCustom02').val(result.content);
        $('#validationCustom03').val(getDate(result.maintenanceTime).datetime());
        $('#addInfoModal').modal();
    })
}

/*删除信息*/
function deleteInfo(e) {
    myConfirm("提示", "是否要删除此信息", function (res) {
        if (res) {
            getJson("/maintenance/deleteMaintenance", {"id": e},'GET',function (result) {
                if (result.code == 200) {
                    myAlert("提示", "删除成功", function () {
                        loadMaintenanceData(toPage);
                        return;
                    });
                } else {
                    myAlert("提示", result.message);
                }
            })
        }
    })
}

function loadMaintenanceData(_pageIndex) {
    $('#addInfoModal').modal("hide");
    showLoading(LOADING);
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage = pageIndex;
    getJson("/maintenance/getMaintenanceInfoByParam", {
            beginTime: $('#searchTimeBegin').val(),
            endTime: $('#searchTimeEnd').val(),
            type: 0,
            pageIndex: pageIndex,
            pageSize: 10
        },'GET',function (result) {
            if (result['code'] == 200) {
                let data = result['payload']['data'];
                setPage($('#page'), pageIndex, result['payload']['pages'], result['payload']['total'], function (num) {
                    loadMaintenanceData(num);
                });
                let order = 1 + 10 * (pageIndex - 1);
                for (let item of data) {
                    item['order'] = order++;
                }
                buildTable($('#maintenance_List'), title, label, data, function (td, label, item) {
                    switch (label) {
                        case 'maintenanceTime':
                            $(td).empty();
                            $(td).text(getDate(item['maintenanceTime']).datetime());
                            break;
                        case 'opera':
                            let edit = createElement('a', td);
                            $(edit).addClass('font-p24');
                            $(edit).attr('href', '##');
                            $(edit).click(function () {
                                editInfo(item['id']);
                            });
                            let del = createElement('a', td);
                            $(del).addClass('font-p24').addClass('delete-option-btn').addClass('ml-2');
                            $(del).attr('href', '##');
                            $(del).click(function () {
                                deleteInfo(item['id']);
                            });
                            let editIcon = createElement('i', edit);
                            $(editIcon).addClass('iconfont').addClass('icon-bianji-');
                            let delIcon = createElement('i', del);
                            $(delIcon).addClass('iconfont').addClass('icon-shanchuicon');
                            break;
                    }
                })
            }
            hideLoading();
        })
}
